package com.example.expandablelistview.listview;

import android.app.ListActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class CursorAdapterEx extends ListActivity implements
		LoaderCallbacks<Cursor> {

	SimpleCursorAdapter mAdapter;

	static final String[] PROJECTION = new String[] {
			ContactsContract.CommonDataKinds.Phone._ID,
			ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
			ContactsContract.CommonDataKinds.Phone.NUMBER };

	static final String SELECTION = "((" + ContactsContract.Data.DISPLAY_NAME
			+ " NOTNULL) AND (" + ContactsContract.Data.DISPLAY_NAME
			+ " != '' ))";

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ProgressBar progressBar = new ProgressBar(this);
		progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		progressBar.setIndeterminate(true);
		getListView().setEmptyView(progressBar);

		ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
		root.addView(progressBar);

		String[] fromColumns = { ContactsContract.Data.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };
		int[] toViews = { android.R.id.text1, android.R.id.text2 };

		mAdapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_2, null, fromColumns,
				toViews, 0);
		setListAdapter(mAdapter);
		getLoaderManager().initLoader(0, null, this);
	}

	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		return new CursorLoader(this,
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION,
				SELECTION, null, null);
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		mAdapter.swapCursor(data);
	}

	public void onLoaderReset(Loader<Cursor> loader) {
		mAdapter.swapCursor(null);
	}

	public void onListItemClick(ListView l, View v, int position, long id) {
		Cursor cursor = mAdapter.getCursor();
		cursor.moveToPosition(position);
		String text = "Select item = " + cursor.getString(1) + " : "
				+ cursor.getString(2);
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

}
